package lengthOfLongestSubstring3;

import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestSubstring {
    public static void main(String[] args) {
        LengthOfLongestSubstring lengthOfLongestSubstring = new LengthOfLongestSubstring();
        System.out.println(lengthOfLongestSubstring.lengthOfLongestSubstring("sfsadfasfrewrr"));
    }

    //最长子串--滑动窗口
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int end = 0, start = 0; end < n; end++) {
            char alpha = s.charAt(end);
            if (map.containsKey(alpha)) { //如果map中有key说明遇到了重复的字符，那么start就需要向右移动吧相同的字符移出当前窗格
                start = Math.max(map.get(alpha), start);
            }
            ans = Math.max(ans, end - start + 1); //将不相同字符长度持续赋值给ans
            map.put(s.charAt(end), end + 1);//end持续往右移动，并将当时end位置放到map
        }
        return ans;
    }


    public int lenMy(String s){

        int start = 0;
        int end = 0;
        int result=0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            end = i;
            char nowChar = s.charAt(end);
            if(map.containsKey(nowChar)){
                start = Math.max(map.get(nowChar), start);
            }
            result = Math.max(result, end - start + 1);
            map.put(s.charAt(end), end + 1);

        }

        return result;

    }



}

